package com.auto.api.core.type.chain;

import com.auto.api.core.type.json.JsonTypeHandler;
import com.auto.api.core.type.json.torna.AbstractTornaApiResultJsonTypeHandler;
import com.auto.api.core.type.json.yapi.AbstractApiResultJsonTypeHandler;
import com.auto.api.core.type.json.yapi.AbstractResultJsonTypeHandler;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.ResolvableType;

/**
 * @program:
 * @description: json结果处理器链
 * @author: liangshf
 * @create: 2020-10-14
 */
public class JsonTypeHandlerChain implements JsonTypeHandler {
    protected List<JsonTypeHandler> handlers = Lists.newArrayList();

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean canCovert(ResolvableType resolvableType) {
        return true;
    }

    /**
     * 新增一个类型处理器
     * @param addHandler JsonTypeHandler
     * @return
     */
    public List<JsonTypeHandler> addHandler(JsonTypeHandler addHandler) {
        handlers.add(0, addHandler);
        return handlers;
    }

    /**
     * 新增一个类型处理器列表
     * @param handlerList List<JsonTypeHandler>
     * @return
     */
    public List<JsonTypeHandler> addHandlerList(List<JsonTypeHandler> handlerList) {
        handlers.addAll(0, handlerList);
        return handlers;
    }

    /**
     * 执行一个类型处理器列表
     * @param resolvableType
     * @return
     */
    public String getJson(ResolvableType resolvableType){
        for (JsonTypeHandler handler : handlers.stream().filter(i -> i instanceof AbstractResultJsonTypeHandler).collect(
            Collectors.toList())) {
            if(handler.canCovert(resolvableType)) {
                return handler.getJson(resolvableType);
            }
        }
        logger.error("未找到对应的类型处理器");
        return "";
    }

    /**
     * 执行一个ResultApiJson类型处理器列表
     * @param resolvableType
     * @return
     */
    public String getApiResultJson(ResolvableType resolvableType){
        for (JsonTypeHandler handler : handlers.stream().filter(i -> i instanceof AbstractApiResultJsonTypeHandler).collect(
            Collectors.toList())) {
            if(handler.canCovert(resolvableType)) {
                return handler.getJson(resolvableType);
            }
        }
        logger.error("未找到对应的类型处理器");
        return "";
    }

    /**
     * 执行一个TornaApiResultJson类型处理器列表
     * @param resolvableType
     * @return
     */
    public String getTornaApiResultJson(ResolvableType resolvableType){
        for (JsonTypeHandler handler : handlers.stream().filter(i -> i instanceof AbstractTornaApiResultJsonTypeHandler).collect(
            Collectors.toList())) {
            if(handler.canCovert(resolvableType)) {
                return handler.getJson(resolvableType);
            }
        }
        logger.error("未找到对应的类型处理器");
        return "";
    }
}